<template>
  <div class="page-container page-container-create">
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>通用促销</el-breadcrumb-item>
        <el-breadcrumb-item>创建单一活动</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <p class="font22 mb20">创建单一活动</p>
    <!-- 添加商品 -->
    <el-dialog :visible.sync="dialogVisibleTwo" title="添加商品" :close-on-click-modal="false">
      <div>
        <div>
          <el-form inline :model="productForm" ref="productForm" :size="size" >
            <div class="col-sm-9">
              <el-form-item label="商品名称：" prop="goodsName" class="w178 mb30" label-width="112px">
                <el-input v-model="productForm.goodsName" auto-complete="off" clearable  placeholder="商品名称" maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="商品编码：" prop="thirdSpuId" class="w178" >
                <el-input v-model="productForm.thirdSpuId" auto-complete="off" clearable  placeholder="商品编码" maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="商品类目：" prop="goodsCategory" class="w178" >
                <el-input v-model="productForm.goodsCategory" auto-complete="off" clearable  placeholder="商品类目" maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="所属店铺名称：" prop="storeName" class="w178">
                <el-input v-model="productForm.storeName" auto-complete="off" clearable  placeholder="所属店铺名称" maxlength="80"></el-input>
              </el-form-item>
            </div>
          </el-form>
          <el-row class="mb30 mt20 t_r">
            <el-button class="resetButton" size="mini" @click="resetProductForm()" icon="el-icon-refresh">重置</el-button>
            <el-button class="searchButton" size="mini" @click="productFormFind()" icon="el-icon-search">搜索</el-button>
            <el-button class="searchButton" size="mini" @click="addAllProduct()">全部添加</el-button>
          </el-row>
        </div>
        <div>
          <el-table
            :data="tableDataTwo"
            @selection-change="addSelectionChangeProduct"
            :header-cell-style="tableHeaderColor"
            ref="multipleTable"
            :row-class-name="tableRowClassName"
            v-loading="tableDataTwoLoading"
            :size="size"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="code" label="商品编码" sortable align="center"></el-table-column>
            <el-table-column prop="chineseName" label="商品名称" align="center"></el-table-column>
            <el-table-column label="商品类目" align="center">
              <template slot-scope="scope">
                {{scope.row.goodsCategory || '-'}}
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="所属店铺" align="center"></el-table-column>
            <el-table-column prop="salePriceScope" label="原价（元）" align="center"></el-table-column>
          </el-table>
          <!--分页栏-->
          <div class="toolbar t_r" v-if="tableDataTwo.length > 0">
            <el-pagination
              @size-change="producthandleSizeChange"
              @current-change="producthandleCurrentChange"
              :current-page="productForm.start"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="productForm.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="productListTotal"
            ></el-pagination>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button class="cancelButton" plain :size="size" @click.native="dialogVisibleTwo = false">取消</el-button>
        <el-button
          :size="size"
          class="searchButton"
          @click.native="dialogVisibleTwo = false"
          @click="productTableData2Click"
          :loading="productEditLoading"
        >确定</el-button>
      </div>
    </el-dialog>

    <!--工具栏-->
    <div class="toolbar">
      <div class="stepset" >
        <ul>
          <li :class="{'active':active>=1}"><span>1</span><p>设置促销规则</p></li>
          <li :class="{'active':active>=2}"><span>2</span><p>设置活动商品</p></li>
          <li :class="{'active':active>=3}"><span>3</span><p>创建成功</p></li>
        </ul>
      </div>
      <div v-show="active==1" class="content create_stepOne createSet create_stepAlso">
        <el-form
          :inline="true"
          :model="filters"
          :rules="filtersRules"
          ref="filters"
          :label-position="labelPosition"
          label-width="140px"
        >
          <div>
            <div class="title">基本设置：</div>
            <div class="item">
              <el-row class="m_b30">
                <el-form-item label="活动名称：" prop="promName" class="wid color999">
                  <el-input
                    type="text"
                    v-model.trim="filters.promName"
                    placeholder="请输入3-60个字符之间"
                    maxlength="60"
                    minlength="3"
                    class="input"
                    clearable
                  />
                </el-form-item>
              </el-row>

              <el-row class="m_b30">
                <el-form-item label="活动时间：" prop="promotionStartEndTime" class="wid w450">
                  <el-date-picker
                    v-model="filters.promotionStartEndTime"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="mini"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="timeCheck"
                  ></el-date-picker>
                </el-form-item>
              </el-row>

            </div>
          </div>

          <!-- <div>
            <div class="item">
              <el-row class="labelAlignment">
                <el-form-item label="活动描述：" prop="description" class="wid">
                  <el-input
                    class="activityDesc"
                    type="textarea"
                    :rows="2"
                    :placeholder="genDescriptionPlaceholder()"
                    v-model="filters.description"
                    clearable
                    maxlength="100"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label class="wid">
                  <div
                    class="desc color666"
                  >注：非必填字段，不填将显示系统默认文案（会存在某些促销类型无系统默认文案）。自定义输入活动规则描述描述后将显示在前台商品详情页中，请慎重填写。</div>
                </el-form-item>
              </el-row>
            </div>
          </div> -->

          <!-- <div class="w100">
            <div class="title">交易规则：</div>
            <div class="item">
              <el-row class="m_b52 labelAlignment" v-if="filters.frontPromType!=19">
                <el-form-item label="是否包邮：" prop="parcelsFlag" class="wid">
                  <el-radio-group v-model="filters.parcelsFlag">
                    <el-radio :label="1" border class="form-radio mr40 radioAlignment w144 t_l noMarginLeft">是</el-radio>
                    <el-radio :label="0" border class="form-radio radioAlignment w144 t_l noMarginLeft">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-row>
            </div>
          </div> -->

          <div class="w100">
            <div class="item">
              <el-row class="m_b52 labelAlignment">
                <el-form-item label="活动参与时间:" class="wid t_r" label-width="122px"  :required="true">
                  <el-input
                    class="activityDesc"
                    type="text"
                    v-model="filters.time"
                    maxlength="2"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row class="m_b52 labelAlignment">
                <el-form-item label="渠道：" class="wid t_r" label-width="122px"  :required="true">
                  <el-select v-model="filters.channelId" placeholder="请选择" size="mini" clearable class="width450">
                    <el-option
                      v-for="item in channelOption"
                      :key="item.id"
                      :label="item.channelName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label="备注：" class="wid">
                  <el-input
                    type="textarea"
                    v-model="filters.remark"
                    @input="changeRemark($event)"
                    placeholder="请输入备注"
                    class="remarks h286"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>

      <!--促销商品列表-->
      <div v-if="active==2" class="tab-container createSet active3">
        <!-- tabs -->
        <el-tabs v-model="productStatusTabs" @tab-click="productTabs">
          <el-tab-pane label="商品" name="1">
            <div class="row-line-button t_r">
              <div style="width:100%">
                <el-button
                  class="searchButton"
                  size="mini"
                  @click="changeSearchMerchantProductFlag"
                  icon="el-icon-search"
                >搜索</el-button>
                <el-button class="searchButton" size="mini" @click="add">添加促销商品</el-button>
                <el-button class="resetButton" @click="batchDelProduct">批量删除</el-button>
              </div>
            </div>

            <el-row>
              <div v-if="searchMerchantProductFlag">
                <el-form
                  :inline="true"
                  :model="merchantProductSearchForm"
                  size="mini"
                  ref="merchantProductSearchForm"
                  class="rightForm"
                >
                  <el-form-item label="店铺：" prop="storeId" class="mb30">
                    <template>
                      <el-select v-model="merchantProductSearchForm.storeId" placeholder="全部" clearable>
                        <el-option
                          v-for="item in promotionStoreTableData"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                          clearable
                        ></el-option>
                      </el-select>
                    </template>
                  </el-form-item>

                  <el-form-item label="商品编码：" prop="mpCode" class="mb30">
                    <el-input v-model="merchantProductSearchForm.mpCode" clearable placeholder="商品编码" maxlength="80"></el-input>
                  </el-form-item>
                  <el-form-item label="商品名称：" prop="mpName" class="mb30">
                    <el-input v-model="merchantProductSearchForm.mpName" clearable placeholder="商品名称" maxlength="80"></el-input>
                  </el-form-item>
                  <el-form-item label="商品类目：" prop="categoryName" class="mb30">
                    <el-input v-model="merchantProductSearchForm.categoryName" clearable placeholder="商品类目" maxlength="80"></el-input>
                  </el-form-item>
                  <el-form-item class="mb30">
                    <el-button class="resetButton" size="mini" @click="resetMerchantProductSearch()">重置</el-button>
                    <el-button class="resetButton" size="mini" @click="merchantProductSearch()">查询</el-button>
                    
                  </el-form-item>
                </el-form>
              </div>
            </el-row>
            <div class="tableTree">
              
              <el-table :data="merchantProductTableData" row-key="id" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                        @selection-change="repelSelectionChange"  class="tableStyle" v-loading="merchantProductTableDataLoading">
                <el-table-column align="left" width="30">
                  <template slot="header" slot-scope="scope">
                    <div class="isAllChecked" v-if="merchantProductTableData.length > 0">
                      <el-checkbox
                        :indeterminate="isIndeterminateProductCheck"
                        v-model="isAllProductChecked"
                        @change="handleCheckedAllProductChange"
                      ></el-checkbox>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="40">
                  <template slot-scope="scope">
                    <el-checkbox
                      :indeterminate="scope.row.isIndeterminateCheck"
                      v-model="scope.row.isCheck"
                      @change="handleCheckedProductChange(scope.row,$event)"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="productCode" label="商品编码" width="200" align="left"></el-table-column>
                <el-table-column prop="productName" label="商品名称" width="200" sortable align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.productName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="storeName" label="商品分类" align="center" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.category}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" align="center" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.stock}}</span>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="storeName" label="所属店铺" align="center" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.storeName}}</span>
                  </template>
                </el-table-column> -->

                <el-table-column prop="salePrice" label="原价（元）" align="center" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.price}}</span>
                  </template>
                </el-table-column>


                <el-table-column
                  prop="contentValue"
                  label="*底价"
                  align="center"
                  width="200"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.floorPrice"
                      @blur="updatePriceOrLimit(scope.row)"
                      :size="size"
                      placeholder="底价"
                      :disabled="scope.row.disabled"
                      oninput="value = value.match(/^\d*(\.?\d{0,2})/g)[0]"
                      clearable
                      maxlength="10"
                    />
                  </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right" align="center" width="300">
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="delMerchantProducts(scope.row.id)"
                      type="text"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页栏-->
              <div class="toolbar t_r">
                <el-pagination
                  @size-change="handleSizeChangeMerchantProductTableData"
                  @current-change="handleCurrentChangeMerchantProductTableData"
                  :current-page="merchantProductSearchForm.start"
                  :page-sizes="[10]"
                  style="float:right;"
                  :page-size="merchantProductSearchForm.limit"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="merchantProductTableDataTotal"
                ></el-pagination>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="tab-container tab-success createSet" v-show="active==3">
        <div class="titleInfo">
          <img src="/static/images/success.png" />
          <span class="font20">活动创建成功!</span>
        </div>
        <div class="step-button2">
          <el-button class="resetButton" plain @click="detailList">查看活动列表</el-button>
        </div>
      </div>
    </div>
    <div class="step-button">
      <el-button
        class="cancelButton"
        :plain="active != 1 && active !=3"
        :size="size"
        v-if="active != 1 && active != 3"
        @click="back"
      >上一步</el-button>
      <el-button class="searchButton" :size="size" @click="next" v-show="active!=3">下一步</el-button>
    </div>
  </div>
</template>

<script>
  import marketRequest from "@/market/request/marketRequest";
  import KtButton from "@/views/Core/KtButton";
  import { format } from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  import { darkmagenta } from "color-name";
  import { quillEditor } from "vue-quill-editor";
  import TreeSelect from "@/views/Core/TreeSelect";
  import "quill/dist/quill.core.css";
  import "quill/dist/quill.snow.css";
  import "quill/dist/quill.bubble.css";
  import { getAllRow, changeChild, changeParent } from "@/assets/js/tableTree.js";
  import {
    singleFrontPromTypesRadio,
    chanelCodesRadio,
    proPlatformRadio,
    proUserTypeRadio,
    proMemberTypeRadio,
    proMemberLevelRadio
  } from "@/market/dict/marketDict";
import { param } from '../../../utils';
  const channelArr = ["bbc"];
  const channelArr1 = ["APP端", "PC端", "微信"];
  const channelArr2 = ["新用户", "老用户"];
  const channelArr3 = ["普通会员"];
  const channelArr4 = ["注册用户", "VIP会员", "金卡"];
  export default {
    name: "Tab",
    components: {
      KtButton,
      TableColumnFilterDialog,
      quillEditor,
      TreeSelect
    },
    created: function() {
      //当前登录用户身份为母平台才获取子平台列表
      if (localStorage.getItem("deptType") && localStorage.getItem("deptType") == 0) {
        this.getChildList();
      }else{
        this.channelChange();

      }
      this.promotionId = this.$route.query.id;
      if (typeof this.$route.query.active != "undefined") {
        this.active = this.$route.query.active;
      }else {
        this.channelChange();
      }

    },
    data() {
      var checkTagName = (rule, value, callback) => {
        var regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im,
          regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
        if (regEn.test(value) || regCn.test(value)) {
          callback(new Error("名称不能包含特殊字符"));
        }
        callback();
      };
      var checkOverlayAppNum = (rule, value, callback) => {
        var regEn = /^\+?[1-9][0-9]*$/;
        if (!regEn.test(value)) {
          callback(new Error("请输入正整数"));
        }
        callback();
      };

      var checkConditonValue = (rule, value, callback) => {
        var r = /^\d+\.?\d{0,2}$/; // 2位小数
        // 如果判断不符合正则，则不是正整数不能提交
        if (!r.test(value)) {
          return callback(new Error("请输入数字(支持2位小数)"));
        } else {
          return callback();
        }
      };
      var checkContentValue = (rule, value, callback) => {
        var reg = /^(?!0(\.0{1,1})?$)(\d(\.\d{1,1})?|10)$/;
        var r = /^\d+\.?\d{0,2}$/; // 2位小数
        if (this.filters.frontPromType == 7 && !reg.test(value)) {
          return callback(new Error("请输入0到10直接的数字(支持1位小数)"));
        }
        if (this.filters.frontPromType == 6 && !r.test(value)) {
          return callback(new Error("请输入数字(支持2位小数)"));
        }
        return callback();
      };
      return {
        channelOption:[],
        auditCount: 0,
        merchantProductTotalCount: 0,
        deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
        // 活动时间校验
        timeCheck: {
          disabledDate: time => {
            if (this.promotionStartEndTime) {
              return (
                time.getTime() < Date.now() - 8.64e7 ||
                time.getTime() > new Date(this.promotionStartEndTime).getTime()
              );
            } else {
              return time.getTime() < Date.now() - 8.64e7;
            }
          }
        },
        storeSearchForm: {
          promotionId: this.promotionId,
          merchantType: "2",
          pageNo: 1,
          pageSize: 10,
          orderBys: {
            f: "create_time",
            s: "desc"
          }
        },

        merchantSearchForm: {
          merchantName: null,
          orgNumber:null,
          promotionId: this.promotionId,
          merchantType: "1",
          pageNo: 1,
          pageSize: 10,
          orderBys: {
            f: "create_time",
            s: "desc"
          }
        },

        filtersRules: {
          contentValue: [
            { required: true, validator: checkContentValue, trigger: "change" }
          ],
          conditionValue: [
            { required: true, validator: checkConditonValue, trigger: "change" }
          ],
          freightValue: [{ validator: checkOverlayAppNum, trigger: "change" }],
          freightReducedValue: [
            { validator: checkOverlayAppNum, trigger: "change" }
          ],
          overlayAppNum: [{ validator: checkOverlayAppNum, trigger: "change" }],

          templateDataForm: {
            templateName: null
          },
          templateDialogVisible: false,
          promName: [
            { required: true, message: "请输入活动名称" },
            {
              min: 3,
              max: 60,
              message: "长度在 3 到 60 个字符",
              trigger: "change"
            }
          ],
          promotionStartEndTime: [
            { required: true, message: "请选择时间", trigger: "blur" }
          ],
          frontPromType: [
            { required: true, message: "请选择促销类型", trigger: "blur" }
          ],
          mainGiftSameFlag: [
            { required: true, message: "请选择赠品类型", trigger: "blur" }
          ],
          overlayAppFlag: [
            { required: true, message: "请选择是否叠加应用", trigger: "blur" }
          ],
          promotionRules: [
            { required: true, message: "请设置优惠设置", trigger: "blur" }
          ],
          parcelsFlag: [
            { required: true, message: "请选择是否包邮", trigger: "blur" }
          ],
          channelCodes: [
            { required: true, message: "请选择使用渠道", trigger: "blur" }
          ],
        },
        mutexDetailDialogVisible: false,
        mutexPromotionTable: [],
        formLabelWidth: "120px",
        tagCategoryList: [
          {
            id: 1,
            categoryName: "标签分类"
          }
        ],
        productPromotionListObject: { productPromotionList: [] },
        productAddSelection: [],
        tableDataTwo: [],
        searchMerchantProductFlag: false,
        merchantProductTableData: [],
        merchantProductTableDataTotal: 0,
        addTagDialogFormVisible: false,
        addTagForm: {
          categoryId: null,
          tagName: null
        },
        addTagRules: {
          categoryId: [
            { required: true, message: "请选择标签分类", trigger: "change" }
          ],
          tagName: [
            { required: true, message: "请输入标签名称", trigger: "blur" },
            {
              min: 1,
              max: 30,
              message: "长度在 1 到 30 个字符",
              trigger: "blur"
            },
            { trigger: "blur", validator: checkTagName }
          ]
        },
        dialogVisibleTwo: false,
        tabsIndex: "first",
        labelPosition: "right",
        productForm: {
          start: 1,
          limit: 10,
          goodsName: null,
          storeName: null,
          thirdSpuId: null,
          goodsCategory: null,
          productName: "",
          productNo: "",
          barCode: "",
          chineseName: "",
          code: ""
        },
        checkFlag:true,
        adminDataForm: {
          auditRemark: null
        },
        adminDataFormRules: {
          auditRemark: [
            { required: true, message: "审核意见不能为空", trigger: "blur" }
          ]
        },
        dialogVisibleAdmin: false,
        shenhe: 0,
        size: "small",
        editDialogVisible: false,
        editDialogVisible2: false,
        url: "./static/shop.png",
        url2: "./static/shop2.png",
        content: null,
        editorOption: {},
        size: "small",
        productVisible: false,
        uploadVisible: false,
        operation: false, // true:商品导入, false:下载模板
        activeName: 0,
        setUp: false,
        search: false,
        tagList: [],
        filters: {
        channelId:"",
          id: null,
          promType: 1,
          labelId: null,
          promName: null,
          frontPromType: 1,
          foldingFlag: 1,
          overLimitRule: 1,
          channelCodes: null,
          proPlatform: [1],
          proUserType: null,
          proMemberType: [1],
          proMemberLevel: [2],
          createMerchantId: 11,
          contentType: 1,
          status: 9,
          rejectCouponsFlag: 0,
          ruleId: null,
          parcelsFlag: 0,
          overlayAppNumFlag: 0,
          overlayAppNum: null,
          description: "",
          conditionValue: null,
          contentValue: null,
          promotionRules: [
            { conditionValue: null, contentValue: null, id: null, level: 1 }
          ],
          mainGiftSameFlag: 1,
          costAllocationFlag: 1,
          parentAllocationScale: null,
          childAllocationScale: null,
          merchantAllocationScale: null,
          storeAllocationScale: null,
          templateFlag: 1,
          templateName: null,
          storeArea: -1,
          userArea: -1,
          promotionStartEndTime: [],
          freightType: 1,
          freightValue: null,
          freightReducedValue: null,
          overlayAppFlag: 0,
          time:''
        },
        editLoading: false,
        merchantProductSearchForm: {
          promotionId: null,
          merchantId: null,
          storeId: null,
          mpCode: null,
          mpName: null,
          categoryName: null,
          start: 1,
          limit: 10
        },
        dataForm: {},
        modalShow: 1,
        multipleSelection: [],
        batchDeleteSelection: [],
        repelSelection: [],
        addSelection: [],
        tableData: [
         
        ],
        active: this.$route.query.active,
        checkAll: false,
        checkAll1: false,
        checkAll2: true,
        checkAll3: false,
        checkAll4: false,
        checkedCities: [110001],
        checkedCities1: ["APP端", "PC端", "微信"],
        checkedCities2: ["新用户", "老用户"],
        checkedCities3: ["普通会员"],
        checkedCities4: ["注册用户", "VIP会员", "金卡"],
        frontPromTypesRadios: singleFrontPromTypesRadio,
        chanelCodesRadios: chanelCodesRadio,
        proPlatformRadios: proPlatformRadio,
        proUserTypeRadios: proUserTypeRadio,
        proMemberTypeRadios: proMemberTypeRadio,
        proMemberLevelRadios: proMemberLevelRadio,
        cities: channelArr,
        cities1: channelArr1,
        cities2: channelArr2,
        cities3: channelArr3,
        cities4: channelArr4,
        isIndeterminate: true,
        isIndeterminate1: true,
        isIndeterminate2: true,
        isIndeterminate3: true,
        isIndeterminate4: true,
        tagCategoryList: [],
        options: [
          {
            value: "1",
            label: "京东直营"
          },
          {
            value: "2",
            label: "淘宝旗舰"
          },
          {
            value: "3",
            label: "良品铺子1店"
          }
        ],
        value5: [],
        options2: [
          {
            value: "1",
            label: "良品铺子"
          }
        ],
        value6: [],
        isClearable: true, // 可清空（可选）
        isAccordion: true, // 可收起（可选）
        valueId: 20, // 初始ID（可选）
        props: {
          // 配置项（必选）
          value: "id",
          label: "name",
          children: "children"
          // disabled:true
        },
        // 选项列表（必选）
        list: [
          { id: 2, parentId: 0, name: "居家生活", rank: 1 },
          { id: 4, parentId: 0, name: "数码家电", rank: 1 },
          { id: 5, parentId: 0, name: "母婴保健", rank: 1 },
          { id: 6, parentId: 0, name: "美食酒水", rank: 2 },
          { id: 7, parentId: 0, name: "个护清洁", rank: 2 },
          { id: 9, parentId: 0, name: "好物甄选", rank: 2 },
          { id: 101, parentId: 2, name: "个护健康", rank: 3 },
          { id: 102, parentId: 2, name: "3C数码", rank: 4 },
          { id: 103, parentId: 2, name: "汽车用品", rank: 5 },
          { id: 202, parentId: 101, name: "按摩电器", rank: 5 },
          { id: 203, parentId: 101, name: "个护美容", rank: 5 }
        ],

        //第一步添加成功赋值
        //外部赋值-----------------start
        promotionId: null,
        auth: 0,
        //外部赋值-----------------start

        promotion: {
          //促销id
          id: "",
          promotionId: "1",
          merchantType: "1"
        },
        pomotionListObject: { pomotionList: [] },

        mainMerchantForm: {
          promotionId: this.promotionId,
          merchantType: "1",
          pageNo: 1,
          pageSize: 10,
          orderBys: {
            f: "create_time",
            s: "desc"
          }
        },
        mainMerchantTableDataTatol: 0,
        //---------------------------商家------------------------------------------------start
        merchantForm: {
          start: 1,
          limit: 10,
          name: null,
          orgNumber: null,
          merchantType:null
        },
        merchantFormStore: {
          start: 1,
          limit: 10
        },
        merchantTableDataTatol: 0,
        merchantTableDataTatolStore: 0,
        merchantTableData: [],
        //选择的商家列表
        merchantTableData2: [],
        promotionStoreTableData: [],
        //---------------------------商家------------------------------------------------end
        storeForm: {
          start: 1,
          limit: 10,
          merchantIds: "",
          storename: "",
          storecode: "",
          orgNumber: "",
          merchantName: "",
          storeType:''
        },

        mainStoreMerchantForm: {
          promotionId: this.promotionId,
          merchantType: "2",
          pageNo: 1,
          pageSize: 10,
          orderBys: {
            f: "create_time",
            s: "desc"
          }
        },
        storeTableDataTatol: 0,
        storeTableData: [],
        //选择店铺
        storeTableData2Tatol: 0,
        storeTableData2: [],
        //选择店铺
        addSelectionStoreTableData2: [],
        merchantTableData2Selection: [],
        merchantTableData2SelectionIndex: 0,
        storeTableDataSelection: [],
        storeTableDataSelectionIndex: 0,

        // -----------------------------------商品开始属性-----------------------------------start

        productTableDataTotal: 0,
        productTableData: [],
        productEditLoading: false,
        productPromotion: {
          //促销id
          promotionId: "1"
        },

        mainProductForm: {
          promotionId: this.promotionId,
          start: 1,
          limit: 10,
          orderBys: {
            f: "create_time",
            s: "desc"
          }
        },

        merchantProductTableDataMutexTotal: 0,
        channelList: [], //渠道Tree List
        channlProps: {
          children: "children",
          label: "childName"
        },

        // -----------------------------------商品结束属性-----------------------------------end

        productStatusTabs: "1" ,   //商品tabs

        mutexMerchantProductTotalCount: 0 ,   //互斥Sku总条数
        mutexProductList: [] ,                //互斥商品List
        mutexProductForm: {
          start : 1,
          limit: 10,
          promotionId: this.promotionId,
          mutexFlag:1,//互斥标识
        },
        mutexProductTotal: 0,                 //互斥分页总条数
        showButtons:true,                     //功能按钮
        mutexPromotionList:[],                //查看详情弹窗
        mutexPromotionListTotal:0,
        mutexPromotionVisible:false,
        mutexPromotionForm:{
          promType: 1,
          start:1,
          limit:10,
        },
        isAllChecked: false,//全选
        isIndeterminateCheck: false,//全选 checkbox 的不确定状态
        allData: [],//全选 操作数据

        isAllProductChecked: false,//全选
        isIndeterminateProductCheck: false,//全选 checkbox 的不确定状态
        allProductData: [],//全选 操作数据

        //会员等级 会员类型
        memberGradeList: [],
        reloadMemLevel: true,

        //会员类型
        memTypeCheckAll: true,
        selectMemTypes:[1,2],
        memTypeIsIndeterminate: false,

        tableDataTwoLoading: false,
        merchantTableData2Loading: false,
        storeTableDataLoading: false,
        merchantProductTableDataLoading: false,
        mutexProductListLoading: false,
        mutexPromotionTableLoading: false,
        mutexPromotionListLoading: false,
        merchantTableDataLoading: false,
        storeTableData2Loading:false,
        userTypeCheckAll: true,
        selectUserType:[1,2],
        userTypeIsIndeterminate: false,
      };
    },
    methods: {
      queryChannelListOther: function() {
      var this_ = this;
      this.utils.request.queryChannelListOther({}, function(res) {
        if (res.code == "0000") {
          this_.channelOption = res.data;
        }
      });
    },
            //新老用户
      handleCheckAllUserTypeChange(val) {
        this.selectUserType = val ? [1,2] : [];
        this.userTypeIsIndeterminate = false;
      },
       handleCheckedUserTypeChange(value) {
          let checkedCount = value.length;
          this.userTypeCheckAll = checkedCount === 2;
          this.userTypeIsIndeterminate = checkedCount > 0 && checkedCount < 2;
       },
      getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
      },
      //使用渠道选中时触发
      channelChange(callback){
        let deptNodeList = [];
        let deptIds = [];
        if(this.deptType == 0){
          deptNodeList = this.$refs.channelTree.getCheckedNodes();
          deptIds = deptNodeList.map((item,index) =>{
            return item.deptId;
          })
          if(deptIds.indexOf("179") == -1){
            deptIds.unshift("179");
            deptNodeList.unshift({"deptId":179,"childName":"卡奥斯运营中心","id":179})
          }
        }else{
          //查询子平台信息
          let deptId = localStorage.getItem("deptId");
          deptIds.push(deptId);
          let userInfo = JSON.parse(localStorage.getItem("user"));
          deptNodeList.push({deptId:userInfo.deptId,"childName":userInfo.deptName,"id":userInfo.businessId})
        }


        this.utils.request.listMemberGradeForMarket({"deptIds": deptIds.join(",")},res=>{
          if(res.code == '0000'){
            let levelList = res.data;
            let restLevelInfo =  [];
            //如果存在排除重新赋值
            this.memberGradeList.forEach(levelItem=>{
              let levelInfo = levelList.find(function(level) {
                return levelItem.deptId == level.deptId;
              })
              if(levelInfo != undefined){
                restLevelInfo.push(levelItem);
              }
            })
            //遍历
            this.memberGradeList = restLevelInfo;
            for(let deptInfo of deptNodeList){
              let levelItem = this.memberGradeList.find(function(level) {
                return deptInfo.deptId == level.deptId;
              })
              if(levelItem != undefined){
                continue;
              }
              //如果不勾选子平台 删除已有子平台

              let levelInfo = levelList.find(function(level) {
                return level.deptId == deptInfo.deptId;
              })
              if(levelInfo == undefined){
                this.memberGradeList.push({ deptId: deptInfo.deptId, childName: deptInfo.childName, businessId: deptInfo.id ,checkAll: true, isIndeterminate: false,  levelSelectList: [], levelList:[]})
              }else{
                //添加数据
                let selectLevelIds = levelInfo.mememberGradeResponseList.map((item,index) =>{
                  return item.id;
                })
                levelInfo.mememberGradeResponseList.forEach(item=>{
                  item.key = this.getUuid();
                })
                this.memberGradeList.push({deptId: deptInfo.deptId, childName: deptInfo.childName, businessId: deptInfo.id ,  levelSelectList: selectLevelIds,  checkAll: true , isIndeterminate: false , levelList:levelInfo.mememberGradeResponseList})
              }
            }
          }else{
            this.memberGradeList = [];
          }
          this.$nextTick(()=>{
            if(callback != undefined){
              callback();
            }
          })
        })
      },


      changeSearchMerchantProductFlag(){
        this.searchMerchantProductFlag = !this.searchMerchantProductFlag;
        this.resetForm("merchantProductSearchForm");
      },
      getPromotionStoreTableData(){
        let this_ = this;
        let param = {"promotionId":this.promotionId,"merchantType":2,"pageNo":1, "pageSize":100000};
        this.utils.request.promotionMerchantList(param, res => {
          if (res.code == "0000") {
            this_.promotionStoreTableData = res.data.list.map((ele, index) => {
              let promotionStore = {};
              promotionStore.id = ele.storeId;
              promotionStore.name = ele.storename;
              return promotionStore;
            });
          }
        });
      },
      /**
       * 查询互斥商品
       */
      getMutexProductList() {
        this.mutexProductListLoading = true;
        var this_ = this;
        this.mutexProductForm.promotionId = this.promotionId;
        marketRequest.getProductListV3(this.mutexProductForm, res => {
          if (res.code == "0000") {
            this_.mutexProductList = res.data.rows;
            this_.mutexProductTotal = res.data.total;
            this_.mutexMerchantProductTotalCount = res.data.totalCount;
            //操作数据
            this_.allData = getAllRow(this_.mutexProductList, []);
            this_.isAllChecked = false;
            this_.isIndeterminateCheck = false;
          }
          this_.$nextTick(() =>{
            this_.mutexProductListLoading = false;
          })

        });
      },
      /**
       * 生效商品 互斥商品tab选中触发
       */
      productTabs(tab){
        if(tab.index==0){
          this.showButtons = true;
        }else{
          this.showButtons = false;
        }
      },

      getPromotionMutexListByProductId(){
        this.mutexPromotionListLoading = true;
        let that = this;
        this.utils.request.getPromotionMutexListByProductId(this.mutexPromotionForm,res=>{
          if(res.code=='0000'){
            that.mutexPromotionList = res.data.rows;
            that.mutexPromotionListTotal = res.data.total;
            that.mutexPromotionVisible = true;
          }
          that.$nextTick(() =>{
            that.mutexPromotionListLoading = false;
          })
        });
      },

      /**
       * 每页条数改变触发
       */
      mutexPromotionListSizeChange(val){

        this.mutexPromotionForm.limit = val;
        this.mutexPromotionForm.start = 1;
        this.getPromotionMutexListByProductId();
      },
      /**
       * 换页刷新
       */
      mutexPromotionListCurrentChange(val){
        this.mutexPromotionForm.start = val;
        this.getPromotionMutexListByProductId();
      },
      checkProductLimits(row){
        var reg = /^(?!0(\.0{1,1})?$)(\d(\.\d{1,1})?|10)$/;//0-10
        var priceReg = /^\d+\.?\d{0,2}$/; // 2位小数
        var regPos = /^[1-9]([0-9]*)$/; // 非负整数

        if(!row.floorPrice || row.floorPrice == ''){
          this.$message({ message: "请输入商品底价", type: "error" });
          return this.checkFlag=false;
        }
        if(!priceReg.test(row.floorPrice)){
          this.$message({ message: "正数，支持输入2位小数", type: "error" });
          return this.checkFlag=false;
        }
        if(Number(row.floorPrice) > Number(row.price)){
          this.$message({ message: row.floorPrice + "不能大于 " + row.price, type: "error" });
          return this.checkFlag=false;
        }
        return this.checkFlag=true;
      },


      getPromotionDetail(promotionId) {
        //获取促销基本信息详情
        let params = { id: promotionId },
          _this = this;
        this.utils.request.queryBargainInfo(params, res => {
          if (res.code == "0000") {
            _this.filters.id = res.data.id;
            _this.filters.promType = res.data.promType;
            _this.filters.promName = res.data.promName;
            _this.filters.description = res.data.description;
            _this.filters.channelCodes = res.data.channelCodes;
            _this.filters.startTime = res.data.startTime;
            _this.filters.endTime = res.data.endTime;
            _this.filters.remark = res.data.remark;
            _this.filters.rejectCouponsFlag = res.data.rejectCouponsFlag;
            _this.filters.parcelsFlag = res.data.parcelsFlag;
            _this.filters.promotionRules = res.data.promotionRules;
            _this.filters.mainGiftSameFlag = res.data.mainGiftSameFlag;
            _this.filters.time = res.data.time;
            _this.filters.channelId=res.data.channelId;
          _this.filters.costAllocationFlag = parseInt(
              res.data.costAllocationFlag
            );
            _this.$set(_this.filters, "promotionStartEndTime", [
              new Date(res.data["startTime"]),
              new Date(res.data["endTime"])
            ]);
          } else {
            alert("获取促销详情失败");
          }
        });
      },
      resetStoreForm() {
        //需要校验的keys
        let keys = ["storeType","merchantName","storecode","storename"]
        //调用校验
        let  boo = this.seachTableUtils.checkFromIsNull(this.storeForm,keys)
        if(!boo){
          return;
        }
        this.resetForm("storeForm");
        this.storeFormFind();
      },
      resetProductForm() {
        //需要校验的keys
        let keys = ["goodsCategory","thirdSpuId","goodsName","storeName"]
        //调用校验
        let  boo = this.seachTableUtils.checkFromIsNull(this.productForm,keys)
        if(!boo){
          return;
        }
        this.resetForm("productForm");
        this.productFormFind();
      },
      resetMerchantForm() {
        //需要校验的keys
        let keys = ["merchantType","name","orgNumber"]
        //调用校验
        let  boo = this.seachTableUtils.checkFromIsNull(this.merchantForm,keys)
        if(!boo){
          return;
        }
        this.resetForm("merchantForm");
        this.merchantFormFind();
      },
      //获取子平台列表
      getChildList() {
        let this_ = this;
        let channel = { childName: "卡奥斯运营中心", id: "179", deptId: "179" };
        this.utils.request.queryChildList({}, res => {
          if (res.code == "0000" && res.data && res.data.length > 0) {
            channel.children = res.data;
            this.channelList.push(channel);
            if (this.promotionId == null) {
              this_.$nextTick(() => {
                this_.$refs.channelTree.setChecked("179", true, false);
                res.data.forEach(item => {
                  this_.$refs.channelTree.setChecked(item.id, true, false);
                });
                //获取选中的deptIds  getMemLevelList
                this.channelChange();
              });
            }
          }
        });
      },
      addAllProduct() {
        let that_ = this;
        // this.productForm.storeIds = this.storeTableData.map((ele, index) => {
        //   return ele.id;
        // });
        let callback = function(res) {
          if (res.code == "0000") {
            that_.dialogVisibleTwo = false
            // 成功查询本地促销商品
            that_.getProductListV2(0, null);
            that_.getMutexProductList();
          }
        };
        this.productForm.promotionId = this.filters.id;
        marketRequest.promotionMerchantProductAddAll(this.productForm, callback);
      },

      getCurrentStep() {
        return this.active - 1;
      },

      resetMerchantProductSearch() {
        //需要校验的keys
        let keys = ["categoryName","mpName","mpCode","storeId"]
        //调用校验
        let  boo = this.seachTableUtils.checkFromIsNull(this.merchantProductSearchForm,keys)
        if(!boo){
          return;
        }
        this.resetForm("merchantProductSearchForm");
        this.merchantProductSearch();
      },
      // 模板下载
      downloadTemplate() {
        window.location.href =
          this.utils.getHost() + "jic-market/resource/download?key=FULL";
      },
      // 批量删除
      batchDelProduct() {
        let ids = [];
        this.allProductData.forEach(function(item,index,array){
          //判断父下面是否全选
          if(item.typeOfProduct == '10' && item.isCheck){
            if(item.children && item.children.length > 0){
              let isCheckItems = item.children.filter(function (subItem, index) {
                return !subItem.isCheck;
              });
              if(!(isCheckItems && isCheckItems.length > 0)){
                ids.push(item.id);
              }
            }else{
              ids.push(item.id);
            }
          }else if(item.typeOfProduct == '20' && item.isCheck){
            ids.push(item.id);
          }
        });
        if (ids.length == 0) {
          this.$message({ message: "未选择删除条目", type: "error" });
          return;
        }

        this.$confirm('确认批量删除已选内容？', "提示", {
          type: "warning",
          closeOnClickModal: false,
        }).then(() => {
          let this_ = this;
          let callback = function(res) {
            if (res.code == "0000") {
              // 成功查询本地促销商品
              this_.getProductListV2(0, null);
            } else {
              this.$message({ message: "删除商品失败", type: "fail" });
            }
          };
          let param = {};
          param.ids = ids;
          marketRequest.promotionMerchantProductDeleteBatch(param, callback);
        }).catch(() => {});
      },

      genDescriptionPlaceholder() {
        let placeholder = "最多输入100个字";
        return placeholder;
      },

      handleCurrentChangeMerchantProductTableData(pageNum) {
        this.merchantProductSearchForm.start = pageNum;
        this.getProductListV2(0, null);
      },
      handleSizeChangeMerchantProductTableData(val) {
        this.merchantProductSearchForm.limit = val;
        this.getProductListV2(0, null);
      },


      /*
    备注无法编辑
   */
      changeRemark(val) {
        this.$forceUpdate();
      },
      merchantProductSearch() {
        this.merchantProductSearchForm.bargainId=this.promotionId;
        this.getProductListV2(0, this.merchantProductSearchForm);
      },
      getProductListV2(type, searchParm) {
        this.merchantProductTableDataLoading = true;
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.isAllProductChecked = false;
            this_.isIndeterminateProductCheck = false;
            if (type == 0 && res.data.total > 0) {
              this_.merchantProductTableData = res.data.rows;
              this_.merchantProductTableDataTotal = res.data.total;
              this_.merchantProductTotalCount = res.data.totalCount;
              this_.allProductData = getAllRow(this_.merchantProductTableData, []);
            } else {
              this_.merchantProductTableData = [];
              this_.merchantProductTableDataTotal = 0;
              this_.merchantProductTotalCount = 0;
            }
          } else {
          }
          this_.$nextTick(() =>{
            this_.merchantProductTableDataLoading = false;
          })
        };
        this.merchantProductSearchForm.promotionId = this.promotionId;
        this.utils.request.queryBargainPage(this.merchantProductSearchForm, callback);

      },
      addPromotionRuleSet() {
        this.filters.promotionRules.push({
          level: this.filters.promotionRules.length + 1
        });
      },
      //更新价格或者限量-todo
      updatePriceOrLimit(val) {
        if(!this.checkProductLimits(val)){
          return;
        }
      },
      //批量添加商品
      productSaveBatch() {
        this.dialogVisibleTwo = !this.dialogVisibleTwo;
        this.productPromotionListObject.productPromotionList.splice(
          0,
          this.productPromotionListObject.productPromotionList.length
        );

        for (let i = 0; i < this.productAddSelection.length; i++) {
          let temp = {};
          temp.promotionId = this.promotionId;
          temp.mpId = this.productAddSelection[i].id;
          temp.mpName = this.productAddSelection[i].chineseName; // 商品名称
          temp.merchantName = this.productAddSelection[i].name; //商家名称
          temp.storeName = this.productAddSelection[i].storeName; //店铺名称
          temp.mpCode = this.productAddSelection[i].code; //商品编码
          temp.mpParentId = this.productAddSelection[i].parentId;
          temp.merchantId = this.productAddSelection[i].merchantId;
          temp.categoryId = this.productAddSelection[i].categoryId;
          temp.picUrl = this.productAddSelection[i].pictureUrl;
          this.productPromotionListObject.productPromotionList.push(temp);
        }

        let callback = res => {
          if (res.code == "0000") {
            // 查询本地促销商品
            this.mainProductTableDataFormFind();
          }
        };

        this.utils.request.promotionMerchantProductSaveBatch(
          this.productPromotionListObject,
          callback
        );
      },

      //确定 选择商品
      productTableData2Click() {
        let this_=this;
        let params={};
        params.bargainId=this.promotionId;
        params.productIds = this.productAddSelection.map(item => {
          return item.id;
        });
       this.utils.request.insertProductBargain(params,function(res){
         if(res.code == "0000"){
           this_.merchantProductSearchForm.bargainId=this_.promotionId;
            this_.getProductListV2(0,this_.merchantProductSearchForm);
            this_.$message({ message: "操作成功", type: "success" });
         }else{
           this_.$message({ message: "操作失败", type: "error" });
         }
       });
      },
      // 选择商品
      addSelectionChangeProduct(val) {
        let this_ = this;
        this_.productAddSelection = val;
      },

      //修改table header的背景色
      tableHeaderColor({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return "background-color:rgb(250,250,250);";
        }
      },
      //table的双色条纹
      tableRowClassName({ row, rowIndex }) {
        if (rowIndex === 1) {
          return "warning-row";
        } else if (rowIndex === 3) {
          return "success-row";
        }
        return "";
      },
      add() {
        this.dialogVisibleTwo = true;
        this.tableDataTwo = [];
        this.productFormFind();
      },
      // 商品方法开始
      productFormFind() {
        this.tableDataTwoLoading = true;
        let that_ = this;
        this.productForm.storeIds = this.storeTableData.map((ele, index) => {
          return ele.storeId;
        });
        this.productForm.promotionId = this.filters.id;
        marketRequest.promotionSpuPageByPromotionId(this.productForm, function(
          resp
        ) {
          if (resp.code == "0000") {
            if(resp.data.rows == null || resp.data.rows.length < 1){
              that_.tableDataTwo = [];
              that_.productListTotal = 0;
            }else{
              that_.tableDataTwo = resp.data.rows.map((ele, index) => {
                let spu = {};
                spu.id = ele.id;
                spu.code = ele.code;
                spu.chineseName = ele.chineseName;
                spu.totalStock = ele.totalStock;
                spu.goodsCategory = ele.fullNamePath;
                spu.merchantName = ele.merchantName;
                spu.storeName = ele.storeName;
                spu.salePriceScope = ele.salePriceWithTax;
                // spu.measureUnit = ele.measureUnit;
                return spu;
              });
              that_.productListTotal = Number(resp.data.total);
            }
          }
          that_.$nextTick(() =>{
            that_.tableDataTwoLoading = false;
          })
        });

      },
      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
        }
      },
      detailList() {
        this.$router.push({
          path: `/pages/promotionManagement/BargainPromotion`
        });
      },


      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
        }
      },
      // 换页刷新
      mainSroreMerchantRefreshPageRequest: function(pageNum) {
        this.mainStoreMerchantForm.pageNo = pageNum;
        // this.mainStoreTableDataFormFind();
      },
      // 换页刷新
      mainSroreMerchantHandleSizeChange: function(pageSize) {
        this.mainStoreMerchantForm.pageNo = 1;
        this.mainStoreMerchantForm.pageSize = pageSize;
        // this.mainStoreTableDataFormFind();
      },

      // 换页刷新
      refreshPageRequestStore: function(pageNum) {
        this.merchantFormStore.start = pageNum;
        // this.merchantFormFind();
        this.storeFormFind();
      },
      // 换页刷新
      handleSizeChangeStore: function(pageSize) {
        this.merchantForm;
        this.merchantFormStore.limit = pageSize;
        this.merchantFormStore.start = 1;
        this.storeFormFind();
      },

      // 换页刷新
      refreshPageRequest: function(pageNum) {
        this.merchantForm.start = pageNum;
        this.merchantFormFind();
      },
      // 换页刷新
      handleSizeChange: function(pageSize) {
        this.merchantForm.limit = pageSize;
        this.merchantForm.start = 1;
        this.merchantFormFind();
      },
      producthandleCurrentChange(pageNum) {
        this.productForm.start = pageNum;
        this.productFormFind();
      },
 
      producthandleSizeChange(pageSize) {
        this.productForm.start = 1;
        this.productForm.limit = pageSize;
        this.productFormFind();
      },

      //查询绑定关系的商家
      mainMerchantFormFind() {
        this.merchantTableData2Loading = true;
        this.merchantSearchForm.merchantType = "1";
        var this__ = this;
        this.merchantSearchForm.promotionId = this.promotionId;
        this.utils.request.promotionMerchantList(
          this.merchantSearchForm,
          function(res) {
            if (res.code == "0000") {
              var ret = [];
              for (var i = 0; i < res.data.list.length; i++) {
                var temp = {};
                temp.id = res.data.list[i].id;
                temp.name = res.data.list[i].merchantName;
                temp.orgNumber = res.data.list[i].orgNumber;
                temp.merchantType = res.data.list[i].merchantTypeManager;
                temp.merchantId = res.data.list[i].merchantId;
                ret.push(temp);
              }
              this__.merchantTableData2 = ret;
              this__.mainMerchantTableDataTatol = res.data.totalCount;
            }
            this__.$nextTick(() =>{
              this__.merchantTableData2Loading = false;
            })

          }
        );
      },

      //活动渠道
      handleCheckAllChange(val) {
        this.filters.channelCodes = val
          ? chanelCodesRadio.map(function(value, index, array) {
            return value.code;
          })
          : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.chanelCodesRadios.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.chanelCodesRadios.length;
      },
      // ------------------------------------商品开始方法-------------------------------------start
      // 换条数刷新
      handleSizeChangeForProduct: function(pageSize) {
        this.productForm.limit = pageSize;
        this.productForm.start = 1;
        this.productFormFind();
      },

      // 换页刷新
      handleCurrentChangeForProduct: function(pageNum) {
        this.productForm.start = pageNum;
        this.productFormFind();
      },

      // 商品多项目选择
      productSelectionChange(val) {
        // this.storeTableDataSelection=val;
      },

      // 选择商品
      addSelectionChangeProduct(val) {
        let this_ = this;
        this_.productAddSelection = val;
      },

      //查询列表商品
      mainProductTableDataFormFind() {
        this.mainProductForm.promotionId = this.promotionId;
        let this_ = this;
        this.utils.request.queryBargainPage(this.mainProductForm,
          function(res) {
            if (res.code == "0000") {
              this_.merchantProductTableData = res.data.rows;
              this_.merchantProductTableDataTotal = res.data.total;
            }
          }
        );
      },

      // ------------------------------------商品结束方法-------------------------------------end

      addActive() {
        this.active = parseInt(this.active)  + 1;
        this.$router.push({ query: { id: this.promotionId ,auth:0,active:this.active} })
        if (this.active > 4) {
          this.$router.push({
            path: "/pages/promotionManagement/singlePromotion"
          });
        }
      },
      back() {
        this.active = parseInt(this.active) - 1;
        this.$router.push({ query: { id: this.promotionId ,auth:0,active:this.active} })
        this.nextOrBack();
      },

      next() {
        let _this = this;
        let callbackUpdate = function(res) {
          if (res.code == "0000") {
            _this.addActive();
            // _this.mainStoreTableDataFormFind();
          } else {
            _this.$message({ message: "操作失败", type: "fail" });
            _this.active = 1;
          }
        };
        //保存活动基础配置
        if (this.active == 1) {
          let this_=this
          this.$refs["filters"].validate(valid => {
            if (valid) {
              this.filters.startTime = this.filters.promotionStartEndTime[0];
              this.filters.endTime = this.filters.promotionStartEndTime[1];
              if(this.deptType == 3){
                this.filters.costAllocationFlag = 1;
                this.filters.storeAllocationScale = 100;
              }

              if (this.promotionId == null) {
                if( new Date(this.filters.startTime) < new Date()){
                  this.$message({
                    message: "开始时间不能小于当前时间,请修改活动时间"
                  });
                  return;
                }
                this.utils.request.promotioneditInfo(this.filters, function(res){
                  if(res.code == '0000'){
                    this_.promotionId = res.data;
                    this_.filters.id = res.data;
                    this_.promotion.promotionId = res.data;
                    this_.mainMerchantForm.promotionId = res.data;
                    this_.mainStoreMerchantForm.promotionId = res.data;
                    this_.active=2;
                  }else{
                    this_.$message({
                    message: "操作失败"
                  });
                  }
                });
              } else {
                if (
                  this.filters.status == 9 &&
                  new Date(this.filters.startTime) < new Date()
                ) {
                  this.$message({
                    message: "草稿状态下开始时间不能小于当前时间,请修改活动时间"
                  });
                } else {
                  this.utils.request.promotionUpdate(
                    this.filters,
                    callbackUpdate
                  );
                }
              }
            }
          });
        }else if (this.active==2) {//更新活动状态
          if (this.active==2 && this.merchantProductTableData.length == 0) {
            _this.$message({ message: "商品未添加", type: "fail" });
            return;
          }
          let params={};
          let productInfo=[];
          params.ids=this.merchantProductTableData.map(item => {
           productInfo.push({
              id:item.id,
              floorPrice:item.floorPrice
            })
            return productInfo;
          });
          params.productInfo=productInfo;
          //修改低价

          _this.utils.request.updateProductBargain(params, function(res){
            if(res.code == '0000'){
               _this.active = 3;
            }else{
               _this.$message({ message: "操作失败", type: "success" });
            }
          });

        }else if (this.active == 4) {
          this.$message({ message: "操作成功", type: "success" });
          return;
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //批量选择删除商品
      handleBatchDeleteSelection(val) {
        this.batchDeleteSelection = val.map(item => {
          return item.id;
        });
      },
      //批量删除商品-todo
      delBatchMerchantProducts(ids) {
        let callback = function(res) {
          if (res.code == "0000") {
            //成功后重新获取一下商家商品列表
          } else {
            alert("删除失败");
          }
        };
        let param = { ids: ids };
        this.utils.request.promotionMerchantProductDeleteBatch(param, callback);
      },

      //删除促销商品-todo
      delMerchantProducts(id) {
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            // 成功查询本地促销商品
            this_.getProductListV2(0, null);
          } else {
            this_.getProductListV2(0, null);
            alert("删除失败");
          }
        };
        let param = {};
        param.id = id;
        marketRequest.promotionMerchantProductDelete(param, callback);
      },

      repelSelectionChange(val) {
        this.repelSelection = val;
      },
      createPage() {
        this.$router.push("/CreatePromotion");
      },
      handleClick(tab, event) {
        if (tab.name == "0") {
          // 触发‘配置管理’事件
          this.first();
        } else {
          // 触发‘用户管理’事件
          this.second();
        }
      },
      first() {
        this.modalShow = 1;
      },
      second() {
        this.modalShow = 2;
      },
      //添加商品弹窗
      productSelectionModal() {
        this.productVisible = true;
      },
      showBatchSetUp() {
        if (this.search == true) {
          this.search = false;
        }
        if (this.setUp == false) {
          this.setUp = true;
        } else if (this.setUp == true) {
          this.setUp = false;
        }
      },
      showQueryCondition() {
        if (this.setUp == true) {
          this.setUp = false;
        }
        if (this.search == false) {
          this.search = true;
        } else if (this.search == true) {
          this.search = false;
        }
      },
      batchReAdd() {
        if (this.multipleSelection.length < 1) {
          this.$message({ message: "请选择要设置的商品", type: "error" });
          return false;
        }
        this.$message({ message: "操作成功", type: "success" });
      },
      updatePriceAndLimit() {},
      importCommodityModal(val) {
        if (val === 1) {
          this.operation = true;
        } else if (val == 2) {
          this.operation = false;
        }
        this.uploadVisible = true;
      },

      nextOrBack(){
        //根据当前url中active参数判断执行第几步方法
        if (this.active){
          if (parseInt(this.active) == 2){
            this.$nextTick(()=>{
              this.getProductListV2(0, null);
              this.getMutexProductList();
              this.getPromotionStoreTableData();
            })
          }
        }
      },
      handleCheckedAllProductChange(value) {
        this.isIndeterminateProductCheck = false;
        this.allProductData.forEach(f => {
          f.isCheck = value;
          f.isIndeterminateCheck = false;
        });
      },
      handleCheckedProductChange(row, checked) {
        if (row.isIndeterminateCheck) {
          row.isCheck = true;
          checked = true;
        }
        row.isIndeterminateCheck = false;
        changeChild(row, checked);
        changeParent(row, this.allProductData);
        this.isAllProductChecked = this.allProductData.every(e => {
          return e.isCheck;
        });
        this.isIndeterminateProductCheck =
          !this.isAllProductChecked &&
          this.allProductData.some(e => {
            return e.isCheck;
          });
      },

    },
    computed: {
      /* 转树形数据 */
      optionData() {
        let cloneData = JSON.parse(JSON.stringify(this.list)); // 对源数据深度克隆
        return cloneData.filter(father => {
          // 循环所有项，并添加children属性
          let branchArr = cloneData.filter(child => father.id == child.parentId); // 返回每一项的子级数组
          branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
          return father.parentId == 0; //返回第一层
        });
      }
    },
    mounted() {
      this.queryChannelListOther()
      this.auth = this.$route.query.auth;
      this.active = this.$route.query.active;
      this.promotionId = this.$route.query.id;

      if (typeof this.$route.query.id != "undefined") {
        this.promotion.id = this.$route.query.id;
        this.getPromotionDetail(this.promotionId);
      }
      this.nextOrBack();
    }
  };
</script>

<style scoped lang="scss">
@import '../../../assets/css/public.scss';
/deep/ .is-bordered{
  padding: 12px 20px 12px 10px;
}
.mleft10 {
  margin-right: 10px;
}
.flexBox{
  display: flex;
  flex-wrap: nowrap;
  align-content: flex-start;
  .child-name{
    flex-shrink: 0;
  }
  .checkboxes{
    display: flex;

  }

}
.w126{
  width: 126px;
}
.oe{
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.width100{
  width: 97px;
}
.w104{
  width: 104px;
}
.ml60{
  margin-left: 60px;
}
.pdl30{
  padding-left: 30px;
}
.pdt20{
  padding-top: 20px;
}
.labelAlignment{
  /deep/ .el-form-item__label{
    height: 33px !important;
    line-height: 33px !important;
  }
}
.w144{
  width: 144px !important;
}
.width450{
  width: 450px !important;
  /deep/ .el-input__inner{
    width: 450px !important;
  }
}
.contentPadding{
  /deep/ .el-form-item__content{
    padding-top: 8px !important;
  }
}
</style>
